import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { subscribeWithSelector } from 'zustand/middleware';

// Type definitions
interface AppConfig {
  theme: 'light' | 'dark' | 'system';
  language: string;
  autoStart: boolean;
  minimizeToTray: boolean;
  notifications: boolean;
  shortcuts: {
    toggleWindow: string;
    newItem: string;
    search: string;
  };
}

interface WindowState {
  isVisible: boolean;
  isMaximized: boolean;
  isMinimized: boolean;
  isFocused: boolean;
  position: { x: number; y: number };
  size: { width: number; height: number };
}

interface User {
  id: string;
  name: string;
  email: string;
}

// App store interface
interface AppStore {
  // State
  config: AppConfig;
  windowState: WindowState;
  user: User | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  lastUpdated: Date | null;

  // Actions
  setConfig: (config: Partial<AppConfig>) => void;
  setWindowState: (state: Partial<WindowState>) => void;
  setUser: (user: User | null) => void;
  setAuthenticated: (authenticated: boolean) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  updateLastUpdated: () => void;
  reset: () => void;
}

// Default configuration
const defaultConfig: AppConfig = {
  theme: 'system',
  language: 'en',
  autoStart: false,
  minimizeToTray: true,
  notifications: true,
  shortcuts: {
    toggleWindow: 'CmdOrCtrl+Shift+H',
    newItem: 'CmdOrCtrl+N',
    search: 'CmdOrCtrl+F',
  },
};

const defaultWindowState: WindowState = {
  isVisible: true,
  isMaximized: false,
  isMinimized: false,
  isFocused: true,
  position: { x: 100, y: 100 },
  size: { width: 1200, height: 800 },
};

// Create the store
export const useAppStore = create<AppStore>()(
  subscribeWithSelector(
    persist(
      set => ({
        // Initial state
        config: defaultConfig,
        windowState: defaultWindowState,
        user: null,
        isAuthenticated: false,
        loading: false,
        error: null,
        lastUpdated: null,

        // Actions
        setConfig: newConfig =>
          set(state => ({
            ...state,
            config: { ...state.config, ...newConfig },
            lastUpdated: new Date(),
          })),

        setWindowState: newState =>
          set(state => ({
            ...state,
            windowState: { ...state.windowState, ...newState },
          })),

        setUser: user =>
          set(state => ({
            ...state,
            user,
            isAuthenticated: !!user,
            lastUpdated: new Date(),
          })),

        setAuthenticated: authenticated =>
          set(state => ({
            ...state,
            isAuthenticated: authenticated,
            user: authenticated ? state.user : null,
          })),

        setLoading: loading =>
          set(state => ({
            ...state,
            loading,
          })),

        setError: error =>
          set(state => ({
            ...state,
            error,
            loading: false,
          })),

        updateLastUpdated: () =>
          set(state => ({
            ...state,
            lastUpdated: new Date(),
          })),

        reset: () =>
          set(() => ({
            config: defaultConfig,
            windowState: defaultWindowState,
            user: null,
            isAuthenticated: false,
            loading: false,
            error: null,
            lastUpdated: null,
          })),
      }),
      {
        name: 'app-store',
        storage: createJSONStorage(() => localStorage),
        partialize: state => ({
          config: state.config,
          user: state.user,
          isAuthenticated: state.isAuthenticated,
        }),
      }
    )
  )
);

// Selectors
export const useConfig = () => useAppStore(state => state.config);
export const useWindowState = () => useAppStore(state => state.windowState);
export const useUser = () => useAppStore(state => state.user);
export const useIsAuthenticated = () =>
  useAppStore(state => state.isAuthenticated);
export const useLoading = () => useAppStore(state => state.loading);
export const useError = () => useAppStore(state => state.error);

// Actions
export const useAppActions = () => {
  const store = useAppStore();
  return {
    setConfig: store.setConfig,
    setWindowState: store.setWindowState,
    setUser: store.setUser,
    setAuthenticated: store.setAuthenticated,
    setLoading: store.setLoading,
    setError: store.setError,
    updateLastUpdated: store.updateLastUpdated,
    reset: store.reset,
  };
};

// Subscribe to config changes
useAppStore.subscribe(
  state => state.config.theme,
  theme => {
    // Apply theme changes to document
    const root = document.documentElement;
    if (theme === 'dark') {
      root.classList.add('dark');
    } else if (theme === 'light') {
      root.classList.remove('dark');
    } else {
      // System theme
      const prefersDark = window.matchMedia(
        '(prefers-color-scheme: dark)'
      ).matches;
      if (prefersDark) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  }
);

// Subscribe to system theme changes
if (typeof window !== 'undefined') {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  mediaQuery.addEventListener('change', e => {
    const { config } = useAppStore.getState();
    if (config.theme === 'system') {
      const root = document.documentElement;
      if (e.matches) {
        root.classList.add('dark');
      } else {
        root.classList.remove('dark');
      }
    }
  });
}

// Export store type for external use
export type { AppStore };
